#!/usr/bin/env python
#
#       Socket.py
#       
#       Copyright 2009 Ben Davis <its.hip@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import pickle
import socket
import threading
import time
import zlib

class Server(threading.Thread):
    """Wrapper around the socket object which automatically handles
    pickling and compression"""
    def __init__(self, addr):
        threading.Thread.__init__(self)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.settimeout(0.01)
        # Connect to the server
        self.socket.connect(addr)
        self.queue = []
        self.lock = threading.Lock()
        self.stop = False
        self.disconnected = False
        
    def send(self, data):
        print "Sending:", data.__class__.__name__
        self.socket.send(zlib.compress(pickle.dumps(data), 9))

    def recv(self, buffer_size):
        data = self.socket.recv(buffer_size)
        if data != '':
            data = pickle.loads(zlib.decompress(data))
            print "Received:", data.__class__.__name__
            return data
        return None
        
    def join(self):
        self.stop = True
        threading.Thread.join(self)

    def run(self):
        while not self.stop and not self.disconnected:
            try:
                # Get the new data from server
                data = self.recv(4096)
                if data is None:
                    # Server disconnected; act appropriately
                    # At the moment we just exit
                    self.disconnected = True
                self.lock.acquire()
                self.queue.append(data)
                self.lock.release()
            except (socket.error, socket.timeout):
                pass
        if not self.disconnected:
            self.socket.close()
    
    def get(self):
        """Get (and clear) the list of packets"""
        self.lock.acquire()
        r = self.queue[:]
        self.queue = []
        self.lock.release()
        return r
        
    def poll(self):
        """Get (and clear) the first packet in the queue"""
        self.lock.acquire()
        r = self.queue.pop(0)
        self.lock.release()
        return r
    
    def wait(self):
        """Wait until a new packet arrives and get it"""
        r = None
        while r is None:
            if len(self.queue) > 0:
                r = self.queue.pop(0)
            time.sleep(0.001)
        return r
